package com.qf.sy2103.ssm.interceptor;

import com.qf.sy2103.ssm.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1 判断用户是否登录过
        final HttpSession session = request.getSession();
        final Object o = session.getAttribute(Constants.USER_LOGIN_SESSION_KEY);
        if (o !=null){  // 登录过了，直接放行
            log.debug("拦截到的路径为：{},放行！",request.getRequestURI());
            return true;
        }
        // 2 如果没有登录，则重定向到登录页面
        response.sendRedirect("/login.html");
        log.debug("拦截到的路径为：{},重定向到登录页面！",request.getRequestURI());
        return false;
    }
}
